package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.LookAdapter;
import com.sxm.yiwei.beans.Look;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class MsgLookActivity extends BaseActivity implements View.OnClickListener{
    private String TAG ="Look";
    private ImageView lookback;
    private SlideListView1 looklist;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private int no = 1;
    private LookAdapter adapter;
    private ImageView nodata;
    private ImageView backmain;
    List<Look.DataBean> list = new ArrayList<Look.DataBean>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msg_look);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        initLookView();
        getLookListData(no);

        adapter = new LookAdapter(MsgLookActivity.this,list);
        looklist.setAdapter(adapter);
        adapter.setOnClickDelete(new LookAdapter.OnClickDelete() {
            @Override
            public void OnDelete(int p) {
                Look.DataBean dataBean = adapter.list.get(p);
                deleteService(dataBean.getId(),p);
            }
        });
        looklist.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem == 0) {
                    View firstVisibleItemView = looklist.getChildAt(0);
                    if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
                        no++;
                        getLookListData(no);
                    }
                } else if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    View lastVisibleItemView = looklist.getChildAt(looklist.getChildCount() - 1);
                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == looklist.getHeight()) {
                        no++;
                        getLookListData(no);
                    }
                }
            }
        });
    }

    private void getLookListData(int no) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETLOOKME);
        params.addHeader("Content-Type","application/json");
        params.addHeader("appId", appId);
        params.addHeader("token", token);
        params.addHeader("userId", userId);
        JSONObject obj = new JSONObject();
        obj.put("pageNo",no+"");
        obj.put("pageSize","20");
        params.addParameter("params",obj.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    getUtilData(result);
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(MsgLookActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getUtilData(String result) {

        JSONObject object = JSON.parseObject(result);
        JSONArray data = object.getJSONArray("data");

        if (data.size()==0){

        }else {
            nodata.setVisibility(View.GONE);
        }
        for (int i = 0; i < data.size(); i++) {
            Look.DataBean dataBean = new Look.DataBean();
            JSONObject obj1 = JSON.parseObject(String.valueOf(data.get(i)));
            String avatar = obj1.getString("avatar");
            String count = obj1.getString("count");
            String id = obj1.getString("id");
            String nickname = obj1.getString("nickname");
            String updateTime = obj1.getString("updateTime");
            dataBean.setAvatar(avatar);
            dataBean.setCount(Integer.valueOf(count));
            dataBean.setId(id);
            dataBean.setNickname(nickname);
            dataBean.setUpdateTime(Long.valueOf(updateTime));
            list.add(dataBean);
        }
    }

    private void deleteService(String id, final int p) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.DELELOOKME);
        params.addHeader("Content-Type","application/json");
        params.addHeader("appId", appId);
        params.addHeader("token", token);
        params.addHeader("userId", userId);
        JSONObject obj = new JSONObject();
        obj.put("viewId",id);
        params.setBodyContent(obj.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Toast.makeText(MsgLookActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                adapter.list.remove(p);
                adapter.notifyDataSetChanged();
                try {
                    looklist.turnToNormal();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                looklist.invalidate();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(MsgLookActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void initLookView() {
        lookback = (ImageView) findViewById(R.id.message_lookback);
        looklist = (SlideListView1) findViewById(R.id.look_list);
        nodata = (ImageView) findViewById(R.id.msglook_nodata);
        backmain = (ImageView) findViewById(R.id.msglook_backmain);
        backmain.setOnClickListener(this);
        lookback.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.message_lookback:
                //startActivity(new Intent(this, MainActivity.class));
                finish();
                break;
            case R.id.msglook_backmain:

                startActivity(new Intent(MsgLookActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
        }
    }
}
